package com.kevin.io.netty.util;

import com.kevin.io.netty.coder.MsgPackDecoder;
import com.kevin.io.netty.coder.MsgPackEncoder;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LengthFieldPrepender;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;

/**
 * @author Kevin Liu
 */
public class ChannelHandlerUtils {

    /**
     * 简单的测试
     * @param handler
     * @return
     */
    public static ChannelHandler firstTest(ChannelHandler handler){
        return new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                socketChannel.pipeline().addLast(handler);
            }
        };
    }

    public static ChannelHandler secondTest(ChannelHandler handler){
        return new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                //超过1024直接报错
                socketChannel.pipeline().addLast(new LineBasedFrameDecoder(1024));
                socketChannel.pipeline().addLast(new StringDecoder());
                socketChannel.pipeline().addLast(handler);
            }
        };
    }

    public static ChannelHandler thirdTest(ChannelHandler handler){
        return new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel socketChannel) throws Exception {
                //socketChannel.pipeline().addLast("frame decoder",new LengthFieldBasedFrameDecoder(65535,0,2,0,2));
                socketChannel.pipeline().addLast("msgpack decoder",new MsgPackDecoder());
               // socketChannel.pipeline().addLast("frame encoder",new LengthFieldPrepender(2));
                socketChannel.pipeline().addLast("msgpack encoder",new MsgPackEncoder());
                socketChannel.pipeline().addLast(handler);
            }
        };
    }
}
